package cn.xydpeng.springframework.beans.factory.support;

import cn.xydpeng.springframework.beans.BeanUtils;
import cn.xydpeng.springframework.beans.BeansException;
import cn.xydpeng.springframework.beans.factory.BeanFactory;

import java.lang.reflect.Constructor;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2022/10/12
 * @description:
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) throws BeansException {
        Class<?> clazz = bd.getBeanClass();
        if (clazz.isInterface()) {
            throw new BeansException("clazz is Interface");
        }
        try {
            Constructor<?> constructor = clazz.getDeclaredConstructor();

            return BeanUtils.instantiateClass(constructor);

        } catch (NoSuchMethodException e) {
            throw new BeansException("instantiate clazz error", e);
        }
    }


    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner, Constructor<?> ctor, Object... args) throws BeansException {

        return BeanUtils.instantiateClass(ctor, args);
    }
}
